package vn.vfriends.vbox.redis.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.ejb.Stateless;
import javax.inject.Inject;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConvertUtilsBean;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.beanutils.converters.DateTimeConverter;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;
import vn.vfriends.vbox.model.File;

/**
 *
 * @author tuancn
 */
@Stateless
public class FileRedis {
    
    public static final String FILE_LIST_KEY = "files:%s";
    
    public static final String FILE_IDS_KEY = "file:ids";
    
    public static final String FILE_KEY = "file:%s";
    
    @Inject
    private Jedis jedis;
    
    public File addFile(Integer accountId, File file) throws Exception {
        long id = jedis.incr(FILE_IDS_KEY);
        file.setId(id);
        
        Pipeline pipeline = jedis.pipelined();
        //  Add to file id list
        pipeline.lpush(String.format(FILE_LIST_KEY, accountId), String.valueOf(id));
        
        //  Add to hash
        Map<String, String> properties = BeanUtilsBean.getInstance().describe(file);
        pipeline.hmset(String.format(FILE_KEY, String.valueOf(id)), properties);
                
        pipeline.sync();
        
        return file;
    }
    
    public List<File> getFiles(Integer accountId, String providerFileId) throws Exception {
        List<File> files = new ArrayList<>();
        List<String> fileIds = jedis.lrange(String.format(FILE_LIST_KEY, accountId), 0, -1);
        if(fileIds != null && !fileIds.isEmpty()) {
            List<Response<Map<String,String>>> responseList = new ArrayList<>();
            
            Pipeline pipeline = jedis.pipelined();
            for(String strFileId : fileIds) {
                responseList.add(pipeline.hgetAll(String.format(FILE_KEY, strFileId)));
            }
            pipeline.sync();
            
            DateTimeConverter dtConverter = new DateConverter();
            dtConverter.setPattern("EEE MMM dd HH:mm:ss 'ICT' yyyy");

            ConvertUtilsBean convertUtilsBean = new ConvertUtilsBean();
            convertUtilsBean.deregister(Date.class);
            convertUtilsBean.register(dtConverter, Date.class);
            
            BeanUtilsBean beanUtilsBean = new BeanUtilsBean(convertUtilsBean, new PropertyUtilsBean());
            
            for (Response<Map<String, String>> properties : responseList) {
                File file = new File();
                beanUtilsBean.populate(file, properties.get());
                files.add(file);
            }
        }
        
        return files;
    }
}
